/*
 * @Author: Kang
 * @Date: 2021-11-28 18:43:11
 * @Last Modified by: Kang
 * @LastEditTime: 2022-06-30 13:27:26
 */
'use strict';
const fs = require('fs');
const path = require('path');
const sendToWormhole = require('stream-wormhole');
const { successRes } = require('../extend/helper');

const Controller = require('egg').Controller;
/**
  * @controller StreamController (上传Stream文件的Controller)
  */
class UploadForStreamController extends Controller {
  /**
   * @summary 上传文件
   * @description 上传文件
   * @router post /api/uploadStream
   * @request formData file *file 文件
   * @response 200 uploadResponse  返回结果。
   */
  async upload() {
    const { ctx } = this;
    // let pathUrl = ""
    let sqlImgUrl = ""
    // if(process.env.NODE_ENV === "production"){
    //   pathUrl = "../public/uploadForStream"
    //   sqlImgUrl = "/upload/file"
    // }else {
    //   pathUrl = "../public/uploadForStream"
    //   sqlImgUrl = "/public/uploadForStream"
    // }
    const stream = await ctx.getFileStream();
    console.log(stream);
    // 获取当前日期，用于文件夹创建
    const dirName = ctx.helper.formatTime(new Date());
    // 指定上传路径
    const uploadBasePath = '../public/uploadForStream';
    // 文件重命名
    const filename = `${ctx.helper.getUUID()}${path.extname(stream.filename)}`;
    const dir = path.join(__dirname, uploadBasePath, dirName);
    const src = path.join(__dirname, uploadBasePath, dirName, filename);
    // 判断是否存在该文件夹，不存在则创建。
    if (!fs.existsSync(dir)) fs.mkdirSync(dir);

    const result = await new Promise((resolve, reject) => {
      const remoteFileStream = fs.createWriteStream(src);
      stream.pipe(remoteFileStream);

      let errFlag;
      remoteFileStream.on('error', err => {
        errFlag = true;
        sendToWormhole(stream);
        remoteFileStream.destroy();
        reject(err);
      });

      remoteFileStream.on('finish', async () => {
        if (errFlag) return;
        resolve(filename);
      });
    });
    ctx.body = successRes({
      filename,
      url: `/public/uploadForStream/${dirName}/${result}`,
    });
  }
}

module.exports = UploadForStreamController;
